package com.my.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.reggie.common.R;
import com.my.reggie.pojo.Employee;
import com.my.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //1.获取传输过来的加密后的密码值
        String encryPassword = employee.getPassword();

        //2.从数据库中获取用户信息
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        //3.如果没有查询到则返回登陆失败查询结果
        if(emp == null){
            return R.error("没有查询到该用户信息！");
        }

        //4.获取注册时保存的随机盐值
        String salt = emp.getSalt();

        //5.将页面提交的密码password进行md5二次加密
        String password = DigestUtils.md5DigestAsHex((salt + encryPassword).getBytes());

        //6.密码比对，如果不一致则返回登陆失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误！");
        }

        //7.查看员工状态是否可用
        if(emp.getStatus() == 0){
            return R.error("该员工已被禁用！");
        }

        //8.登录成功，将员工id存入Session对象并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出登录成功");
    }

    /**
     * 添加员工
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        //生成随机salt值
        String salt = RandomStringUtils.randomAlphanumeric(5);
        //设置随机盐值
        employee.setSalt(salt);
        //设置密码二次加密
        employee.setPassword(DigestUtils.md5DigestAsHex((salt + employee.getPassword()).getBytes()));

        // employee.setCreateTime(LocalDateTime.now());
        // employee.setUpdateTime(LocalDateTime.now());

        //设置创建者id
        // Long createId = (Long) request.getSession().getAttribute("employee");
        // employee.setCreateUser(createId);
        // employee.setUpdateUser(createId);
        // log.info("新增员工，员工信息为{}",employee);

        boolean save = employeeService.save(employee);
        if(save){
            return R.success("添加成功！");
        }
        return R.error("添加失败！");
    }

    /**
     * 分页查询
     * @param page  //当前页码
     * @param pageSize //每页显示条数
     * @return  //R<IPage<Employee>>
     */
    @GetMapping("/page")
    public R<IPage<Employee>> page(int page,int pageSize,String name){
        //构造分页构造器
        IPage<Employee> page1 = new Page<>(page,pageSize);
        //构造条件过滤器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        //添加过滤条件
        lqw.like(name != null,Employee::getName,name);
        //添加排序条件，按照员工创建时间排序
        lqw.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(page1,lqw);
        return R.success(page1);
    }

    /**
     * 修改员工信息
     * @param employee  //传入的员工id及状态信息
     * @return //R<String>
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Employee employee){
        // Long id = (Long) request.getSession().getAttribute("employee");
        // employee.setUpdateUser(id);
        // employee.setUpdateTime(LocalDateTime.now());
        // log.info(employee.toString());
        boolean b = employeeService.updateById(employee);
        if(b){
            return R.success("修改成功！");
        }
        return  R.error("修改失败！");
    }

    /**
     * 按id查询
     * @param id  //传入的id，String类型
     */
    @GetMapping(value = "/{id}")
    public R<Employee> getById(@PathVariable("id")String id){
        long Id = Long.parseLong(id);
        Employee employee = employeeService.getById(Id);
        return R.success(employee);
    }
}
